<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElInput, ElSelect, ElOption, ElButton, ElLoading } from 'element-plus'
import { getCoursePage, chooseCourse } from '@/api/student'
import { getMajorList } from '@/api/major'
import courseApi from '@/api/course'
import auth from '@/utils/auth'
import { useRouter } from 'vue-router'

// 路由
const router = useRouter()

// 响应式数据
const courses = ref([])  // 课程列表
const majors = ref([])  // 专业列表
const coursesList = ref([])  // 所有课程列表
const loading = ref(false)  // 加载状态
const total = ref(0)  // 总条数

// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)

// 筛选条件
const filters = ref({
  teacherName: '',
  className: '',
  majorId: '',
  courseId: '',
  remaining: null
})
const remainingSwitch = ref(false)

// 加载课程列表
const loadCourses = async () => {
  loading.value = true
  try {
    // 验证参数
    const pageParams = {
      pageNum: parseInt(pageNum.value) || 1,
      pageSize: parseInt(pageSize.value) || 10
    }
    
    const filterParams = {}
    // 只添加非空筛选条件
    if (filters.value.teacherName && filters.value.teacherName.trim()) {
      filterParams.teacherName = filters.value.teacherName.trim()
    }
    if (filters.value.className && filters.value.className.trim()) {
      filterParams.className = filters.value.className.trim()
    }
    if (filters.value.majorId) {
      filterParams.majorId = filters.value.majorId
    }
    if (filters.value.courseId) {
      filterParams.courseId = filters.value.courseId
    }
    if (filters.value.remaining !== '' && filters.value.remaining !== null) {
      filterParams.remaining = filters.value.remaining
    }
    
    const params = { ...pageParams, ...filterParams }
    console.log('发送请求参数:', params)
    
    // 调用API
    const res = await getCoursePage(params)
    console.log('API响应:', res)
    
    // 处理响应
    console.log('完整响应数据:', res)
    if (res && res.code === 200) {
      // 成功响应
      courses.value = res.data?.records || []
      total.value = res.data?.total || 0
      console.log('成功获取课程列表:', courses.value.length, '条记录')
    } else {
      // 失败响应
      console.error('获取课程失败:', res?.msg || '未知错误')
      alert(res?.msg || '获取课程列表失败，请稍后重试')
    }
  } catch (error) {
    console.error('获取课程列表异常:', error)
    // 使用标准的alert代替ElMessage
    alert('网络错误，请检查您的网络连接或稍后重试')
  } finally {
    loading.value = false
  }
}

// 分页变化
const handleCurrentChange = (val) => {
  pageNum.value = val
  loadCourses()
}

// 每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  pageNum.value = 1  // 重置到第一页
  loadCourses()
}

// 搜索
const handleSearch = () => {
  pageNum.value = 1  // 重置到第一页
  loadCourses()
}

// 处理专业选择变化
const handleMajorChange = (majorId) => {
  console.log('选择的专业ID:', majorId)
  // majorId已通过filters.majorId绑定，会自动传递到loadCourses中的查询参数
  // 如果需要在选择专业时立即搜索，可以在这里调用loadCourses()
}

// 处理课程选择变化
const handleCourseChange = (courseId) => {
  console.log('选择的课程ID:', courseId)
  // courseId已通过filters.courseId绑定，会自动传递到loadCourses中的查询参数
  // 如果需要在选择课程时立即搜索，可以在这里调用loadCourses()
}

// 处理余量筛选开关变化
const handleRemainingChange = (value) => {
  console.log('余量筛选开关状态:', value)
  if (value) {
    // 打开时，筛选无余量课程
    filters.value.remaining = 0
  } else {
    // 关闭时，不筛选，查看所有课程
    filters.value.remaining = null
  }
  // 状态变化时自动搜索
  loadCourses()
}

// 重置筛选条件
const resetFilters = () => {
  filters.value = {
    teacherName: '',
    className: '',
    majorId: '',
    courseId: '',
    remaining: null
  }
  remainingSwitch.value = false
  pageNum.value = 1
  loadCourses()
}

// 选课
const selectCourse = async (courseId) => {
  try {
    // 假设从课程列表中找到对应的课程信息
    const course = courses.value.find(item => item.id === courseId)
    if (!course) {
      alert('未找到该课程信息')
      return
    }
    
    // 从token中获取用户ID
    const userId = auth.getUserId();
    if (!userId) {
      ElMessage.error('无法获取用户信息，请重新登录');
      return;
    }
    
    // 创建符合后端要求的UserClass对象
    const userClassData = {
      userId: userId, // 从token中提取的用户ID
      classId: courseId, // 使用课程ID作为classId
      // 可以根据后端需求添加其他必要字段
    }
    
    // 调用选课API
    const res = await chooseCourse(userClassData)
    console.log('选课API响应:', res)
    
    // 处理响应
    if (res && res.code === 200) {
      // 选课成功
      alert('选课成功')
      // 重新加载课程列表以更新数据
      loadCourses()
    } else {
      // 选课失败
      alert('选课失败: ' + (res?.msg || '未知错误'))
    }
  } catch (error) {
    console.error('选课过程中发生错误:', error)
    alert('网络错误，请检查您的网络连接或稍后重试')
  }
}

// 获取专业列表
const fetchMajors = async () => {
  try {
    console.log('开始获取专业列表')
    const response = await getMajorList()
    console.log('专业列表响应:', response)
    
    if (response && response.code === 200 && response.data) {
      majors.value = response.data
      console.log('专业列表:', majors.value)
    } else {
      console.error('获取专业列表失败:', response?.msg || '未知错误')
    }
  } catch (error) {
    console.error('获取专业列表异常:', error)
  }
}

// 获取课程列表
const fetchCoursesList = async () => {
  try {
    console.log('开始获取课程列表')
    const response = await courseApi.getAllCourses()
    console.log('课程列表响应:', response)
    
    if (response && response.code === 200 && response.data) {
      coursesList.value = response.data
      console.log('课程列表:', coursesList.value)
    } else {
      console.error('获取课程列表失败:', response?.msg || '未知错误')
    }
  } catch (error) {
    console.error('获取课程列表异常:', error)
  }
}

// 生命周期钩子 - 组件挂载时加载数据
onMounted(() => {
  loadCourses()
  fetchMajors()
  fetchCoursesList()
})
</script>

<template>
  <div class="course-selection">
    <h2>课程选择</h2>
    <div class="filter-section">
      <el-input
          v-model="filters.className"
          placeholder="班级名称"
          class="filter-input"
          clearable
      />
      <el-input
        v-model="filters.teacherName"
        placeholder="教师姓名"
        class="filter-input"
        clearable
      />

      <el-select
        v-model="filters.majorId"
        placeholder="专业"
        class="filter-input"
        clearable
        @change="handleMajorChange"
      >
        <el-option 
          v-for="major in majors" 
          :key="major.majorId || major.id" 
          :label="major.majorName" 
          :value="major.majorId || major.id"
        />
      </el-select>
      <el-select
        v-model="filters.courseId"
        placeholder="课程"
        class="filter-input"
        clearable
        @change="handleCourseChange"
      >
        <el-option 
          v-for="course in coursesList" 
          :key="course.courseId || course.id" 
          :label="course.courseName" 
          :value="course.courseId || course.id"
        />
      </el-select>
      <div class="filter-switch-container">
        <span>筛选无余量课程</span>
        <el-switch
          v-model="remainingSwitch"
          @change="handleRemainingChange"
          active-text="开启"
          inactive-text="关闭"
        />
      </div>
      <el-button type="primary" @click="handleSearch">搜索</el-button>
      <el-button @click="resetFilters">重置</el-button>
    </div>
    
    <!-- 课程列表 -->
    <el-table
      v-loading="loading"
      :data="courses"
      style="width: 100%"
      border
    >
      <el-table-column prop="className" label="班级名称" width="280" />
      <el-table-column prop="teacherName" label="教师姓名" width="120" />
      <el-table-column prop="majorName" label="专业" width="150" />
      <el-table-column prop="courseName" label="课程" width="200" />
<!--      <el-table-column prop="remaining" label="剩余名额" width="80" />-->
      <el-table-column prop="classroom" label="上课地点" width="120" />
      <el-table-column label="时间安排" width="200">
        <template #default="scope">
          <div v-if="scope.row.classroom === '无上课地点'">——</div>
          <div v-else>
            第{{ scope.row.startWeek }}-{{ scope.row.endWeek }}周<br>
            星期{{ scope.row.day }}
            第{{ scope.row.startTime }}-{{ scope.row.endTime }}节
          </div>
        </template>
      </el-table-column>
      <el-table-column label="选课情况" width="100">
        <template #default="scope">
          {{ scope.row.existing }}/{{ scope.row.number }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" fixed="right">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="selectCourse(scope.row.id)"
            :disabled="scope.row.remaining === 1"
          >
            {{ scope.row.remaining === 1 ? '已满' : '选课' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        :current-page="pageNum"
        :page-size="pageSize"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
  </div>
</template>

<style scoped>
.course-selection {
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  margin-bottom: 20px;
  color: #303133;
}

.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.filter-input {
  width: 180px;
}

.filter-switch-container {
  display: flex;
  align-items: center;
  margin-right: 10px;
}

.filter-switch-container span {
  margin-right: 10px;
  white-space: nowrap;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>